package com.zf.yichat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.dto.PacketSendRequest;
import com.zf.yichat.mapper.NoticeMapper;
import com.zf.yichat.model.Notice;
import com.zf.yichat.service.PushService;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.common.OKHttpUtil;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.codec.binary.Base64;
import org.hibernate.validator.internal.util.Contracts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 15:00 2019/8/26 2019
 */
@Service
public class PushServiceImpl implements PushService {


    private String url = "https://bjapi.push.jiguang.cn/v3/push";

    @Value("${st.im_uri}")
    private String imUri;

    @Autowired
    private ConfigSet configSet;

    @Autowired
    private NoticeMapper noticeMapper;

    private Logger logger = LoggerFactory.getLogger(PushServiceImpl.class);


    @Override
    public void createUser(String username, String password) {

        Map<String, String> header = new HashMap<>();
        try {
            header.put("Content-Type", "application/json");
            header.put("Authorization", "Basic " + new Base64().encodeToString((configSet.getPush().getKey() + ":" + configSet.getPush().getSecret()).getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String data = "{\n" +
                "    \"username\": \"" + username + "\",\n" +
                "    \"password\": \"" + password + "\"\n" +
                "}";

        String res = OKHttpUtil.httpPostJson("https://api.im.jpush.cn/v1/users/", data, header);

        Contracts.assertTrue(res.contains("error"), "IM注册失败");
    }

    @Async
    @Override
    public void sendAll(String title, String content, boolean save) {

        if (!configSet.getPush().isStatus()) {
            logger.debug("推送状态关闭");
            return;
        }

        String data = "{\n" +
                "   \"platform\": [\"ios\",\"android\"]," +
                "   \"audience\" : \"all\"," +
                "   \"options\" : {\"apns_production\":\"True\"}," +
                "   \"notification\" : {\n" +
                "      \"alert\" :\"" + title + "\"," +
                "      \"ios\" : {" +
                "         \"badge\" :  1," +
                "         \"sound\" :  \"default\"" +
                "} \n" +

                "   }\n" +
                "}";
        Map<String, String> header = new HashMap<>();
        try {
            header.put("Content-Type", "application/json");
            header.put("Authorization", "Basic " + new Base64().encodeToString((configSet.getPush().getKey() + ":" + configSet.getPush().getSecret()).getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String res = OKHttpUtil.httpPostJson(url, data, header);
        JSONObject object = JSON.parseObject(res);
//        Contracts.assertTrue(Objects.isNull(object.getJSONObject("error")), "发送失败！" + object.getJSONObject("error").getString("code"));

        //全局通知成功后记录
        if (save) {
            insertNotice(0l, title, content);
        }
    }

    private void insertNotice(Long userId, String title, String content) {
        Notice notice = new Notice();
        notice.setUserId(userId);
        notice.setContent(content);
        notice.setTitle(title);
        notice.setType(0);
        noticeMapper.insertSelective(notice);
    }

    @Override
    @Async
    public void sendGroup(Integer groupId, String title, String content, boolean save) {
        if (!configSet.getPush().isStatus()) {
            logger.debug("推送状态关闭");
            return;
        }
        String data = "{\n" +
                "   \"platform\": [\"ios\",\"android\"]," +
                "   \"options\" : {\"apns_production\":\"True\"}," +
                "   \"audience\" : {\"tag_and\":[\"" + groupId + "\"]}," +
                "   \"notification\" : {\n" +
                "      \"alert\" :\"" + title + "\"," +
                "      \"ios\" : {" +
                "         \"badge\" :  1," +
                "         \"sound\" :  \"default\"" +
                "} \n" +
                "   }\n" +
                "}";
        Map<String, String> header = new HashMap<>();
        try {
            header.put("Content-Type", "application/json");
            header.put("Authorization", "Basic " + new Base64().encodeToString((configSet.getPush().getKey() + ":" + configSet.getPush().getSecret()).getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String res = OKHttpUtil.httpPostJson(url, data, header);

        System.out.println(res);
        JSONObject object = JSON.parseObject(res);

        //Contracts.assertTrue(!object.containsKey("error"), "群推送发送失败");
        if (save) {
            insertNotice(groupId.longValue(), title, content);
        }
    }

    @Async
    @Override
    public void sendSingle(Long userId, String title, String content, boolean save) {
        if (!configSet.getPush().isStatus()) {
            logger.debug("推送状态关闭");
            return;
        }
        //title = userService.selectById(userId).getNick();
        String data = "{\n" +
                "   \"platform\": [\"ios\",\"android\"]," +
                "   \"options\" : {\"apns_production\":\"True\"}," +
                "   \"audience\" : {\"alias\":[\"" + userId + "\"]}," +
                "   \"notification\" : {\n" +
                "      \"alert\" :\"" + title + "\"," +
                "      \"ios\" : {" +
                "         \"badge\" :  1," +
                "         \"sound\" :  \"default\"" +
                "} \n" +

                "   }\n" +
                "}";
        Map<String, String> header = new HashMap<>();
        try {
            header.put("Content-Type", "application/json");
            header.put("Authorization", "Basic " + new Base64().encodeToString((configSet.getPush().getKey() + ":" + configSet.getPush().getSecret()).getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String res = OKHttpUtil.httpPostJson(url, data, header);
        System.out.println(res);

        JSONObject object = JSON.parseObject(res);

        //Contracts.assertTrue(!object.containsKey("error"), "单人推送失败");
        if (save) {
            insertNotice(userId, title, content);
        }
    }

    /**
     * 体现审核-线下转账功能
     * @param type
     * @param bankInfo
     * @param ctime
     * @param envId
     * @param userId
     * @param pushContent
     * @param money
     * @param content
     * @param save
     */
    @Async
    @Override
    public void sendServiceSingle(Integer type, String bankInfo, String ctime, Long envId, Long userId, String pushContent, BigDecimal money, String content, boolean save) {
        PacketSendRequest request = new PacketSendRequest();
        request.setContent(content);
        request.setBankInfo(bankInfo);
        request.setBankInfo(ctime);
        request.setEnvMsg("gdjsalgjow390jt3ngflsjg93j4tg3wmn4gw0m342gmsmvdlsmg03");
        try {
            request.setFrom(N3d.encode(configSet.getMoneyHelper()));
            request.setTo(N3d.encode(userId));
            request.setUserId(N3d.encode(userId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setPushContent(pushContent);
        request.setRedpacketMoney(money);
        request.setEnvId(envId);
        request.setType(type);
        OKHttpUtil.httpPostJson(imUri + "misc/send/system", JSONObject.toJSONString(request));
        if (save) {
            insertNotice(userId, pushContent, content);
        }
    }

    @Override
    public FsResponse sendMsg(Long userId, String title, String content, String platform, boolean save) {
        if (!configSet.getPush().isStatus()) {
            return FsResponseGen.failMsg("推送状态关闭");
        }
//        String platformStr = "[\"ios\",\"android\"]";
//        String audienceStr = "\"all\"";
//        if (Objects.nonNull(platform)) {
//            platformStr = "[\"" + platform + "\"]";
//        }
//        if (Objects.nonNull(userId)) {
//            audienceStr = "{\"alias\":[\"" + userId + "\"]}";
//        }
//
//        String data = "{\n" +
//                "   \"platform\":" + platformStr + "," +
//                "   \"options\" : {\"apns_production\":\"True\"}," +
//                "   \"audience\" : " + audienceStr + "," +
//                "   \"notification\" : {\n" +
//                "      \"alert\" :\"" + title + "\"," +
//                "      \"ios\" : {" +
//                "         \"badge\" :  1," +
//                "         \"sound\" :  \"default\"" +
//                "} \n" +
//
//                "   }\n" +
//                "}";
//        Map<String, String> header = new HashMap<>();
//        try {
//            header.put("Content-Type", "application/json");
//            header.put("Authorization", "Basic " + new Base64().encodeToString((configSet.getPush().getKey() + ":" + configSet.getPush().getSecret()).getBytes("utf-8")));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        String res = OKHttpUtil.httpPostJson(url, data, header);
//        System.out.println(res);
//        JSONObject object = JSONObject.parseObject(res);
////        {"msg_id":"2251904487956988","error":{"code":1011,"message":"cannot find user by this audience or has been inactive for more than 255 days"}}
//
//        JSONObject errer = object.getJSONObject("error");
//        if (Objects.nonNull(errer)) {
//            return FsResponseGen.failMsg(errer.getString("message"));
//        } else {
            if (save) {
                insertNotice(userId, title, content);
            }
            return FsResponseGen.success();
       // }
    }

    public static void main(String[] args) {
        Map<String, String> header = new HashMap<>();
        try {
            header.put("Content-Type", "application/json");
            header.put("Authorization", "Basic " + new Base64().encodeToString(("7251d9fa2d1eda947c24c03f:7e23c1750710b868aa4a3557").getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String data = "[{\n" +
                "    \"username\": \"" + 112111 + "\",\n" +
                "    \"password\": \"" + 111111 + "\"\n" +
                "}]";

        String res = OKHttpUtil.httpPostJson("https://api.im.jpush.cn/v1/users/", data, header);

        System.out.println(res);
        //Contracts.assertTrue(org.apache.commons.lang3.StringUtils.isBlank(object.getString("error")), "注册失败！" + object.getJSONObject("error").getString("code"));
    }
}
